package dbinit;


import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import core.address.model.continent.Continent;
import core.address.model.country.Country;
import core.util.HibernateCoreUtil;

public class InitCountry
{
	public static Country getCountryByName(String name)
	{
		Country co = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try
		{
			transaction = session.beginTransaction();
			co  = (Country)session.createQuery("from Country c where c.countryName='"+name+"'").uniqueResult();
			transaction.commit();
		}
		catch(HibernateException e)
		{
			e.printStackTrace();
		}
		return co;
	}
	public static Country getCountryByUuid(Long uuid)
	{
		Country c = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				c = (Country) session.get(Country.class, uuid);
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return c ;
	}
	public static Long doinit(String countryName , Continent continent,String abbreviation)
	{
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Country country = getCountryByName(countryName);
		if(country == null)
		{
			country = new Country();
		}
		country.setCountryName(countryName);
		country.setContinent(continent);
		country.setAbbreviation(abbreviation);
		Long uuid = null;
		try
		{
			transaction = session.beginTransaction();
			country = (Country)session.merge(country);
			transaction.commit();
			uuid = country.getUuid();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally
		{
			session.close();
		}
		return uuid ;
	}
}
